<?php

class grade_item_controller {
	
	private $params = NULL;
	
	function __construct($params) {
		$this->set_params($params);
		$this->init_access();
	}
	
	function __destruct() {
		
	}
	
	function set_params($params) {
		$this->params = $params;
	}
	
	function init_access() {
		global $authentication;
		$access = ACCESS_GROUP_ADMIN;
		if (! $authentication->have_access($access)) {
			$authentication->access_denied();
		}
	}
	
	/**
	 * Показывает форму добавления заголовка оценки
	 */
	private function show_add_form() {
		global $CFG;
		
		include_once($CFG->app_dir . '/course/class.course_categories.php');
		include_once($CFG->lib_dir . '/views/class.view.php');
		
		$course_categories = new course_categories();
		
		$view = new view(
			__DIR__ . '/views/grade_item_add.php'
		);
		$view->render();
	}
	
	private function load_categories() {
		global $CFG;
		
		include_once($CFG->app_dir . '/course/class.course_categories.php');
		include_once($CFG->lib_dir . '/views/class.view.php');
		
		$course_categories = new course_categories();
		
		$view = new view(
			__DIR__ . '/views/grade_item_load_course_categories.php', 
			array(
				'parent_id' => $_GET['parent_id'],
				'categories' => $course_categories->get_courses_categories($_GET['parent_id']),
			)
		);
		$view->render_partial();
	}
	
	private function load_courses() {
		global $CFG;
		include_once($CFG->app_dir . '/course/class.course_categories.php');
		include_once($CFG->lib_dir . '/views/class.view.php');
		
		$course_categories = new course_categories();
		
		$view = new view(
			__DIR__ . '/views/grade_item_load_courses.php', 
			array(
				'courses' => $course_categories->get_courses($_POST['parent_id']),
			)
		);
		$view->render_partial();
	}
	
	/**
	 * Добавляет заголовки оценок к выбранным предметам
	 */
	private function add_grade_item() {
		global $CFG;
		include_once($CFG->app_dir . '/grade_item/class.grade_item.php');
		$grade_item = new grade_item();
		
		
		$courses_id = (! empty($_POST['courses'])) ? explode(',', $_POST['courses']) : NULL;
		$grade_item->set_itemname($_POST['itemname']);
		$grade_item->set_grademax($_POST['grademax']);
		$grade_item->set_grademin($_POST['grademin']);
		$grade_item->set_category_name($_POST['category-name']);
		$grade_item->set_locktime($_POST['locktime-day'], $_POST['locktime-month'], $_POST['locktime-year']);
		
		if (isset($courses_id)) {
			$grade_item->add($courses_id);
		} else {
			echo "<p>Выберите курсы, к которым нужно добавить элемент оценивания</p>";
		}
	}
	
	function action_add() {
		if ($this->params[0] == 'show') {
			$this->show_add_form(); // добавить параметр родительского элемента
		} else if ($this->params[0] == 'get_categories') {
			$this->load_categories();
		} else if ($this->params[0] == 'get_courses') {
			$this->load_courses();
		} else if ($this->params[0] == 'action') {
			$this->add_grade_item();
		}
	}
}

?>
